package org.example.system.controller;

import com.alibaba.fastjson2.JSON;
import com.baomidou.mybatisplus.core.metadata.IPage;
import lombok.extern.slf4j.Slf4j;
import org.example.system.entity.Remark;
import org.example.system.entity.Post;
import org.example.system.service.PostService;
import org.example.system.service.RemarkService;
import org.example.utils.R;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

/**
 * 评论控制层
 */
@RestController
@Slf4j
@RequestMapping("/app/remark")
public class RemarkController {
    @Autowired
    private RemarkService remarkService;
    @Autowired
    private PostService postService;

    /**
     * 按分页查询联查用户表
     * @param remark
     * @return
     */
    @GetMapping("/list")
    public R list(Remark remark){
        IPage<Remark> page = remarkService.select(remark);
        log.info("------------ RemarkController | list | selectPage | return : {} ", JSON.toJSONString(page));
        return R.ok(page);
    }

    /**
     * 添加评论
     * @param remark
     * @return
     */
    @PostMapping("/add")
    public R add(@RequestBody Remark remark){
        log.info("--------- RemarkController | add | input : {}", JSON.toJSON(remark));
        int row = remarkService.add(remark);
        if(row <= 0){
            return  R.fail("添加失败");
        }
        Post post = postService.getOne(remark.getPostId());
        post.setId(remark.getPostId());
        post.setRemarkCount(post.getRemarkCount() + 1);
        postService.update(post);
        return R.ok("添加成功");
    }

    /**
     * 修改
     * @param remark
     * @return
     */
    @PutMapping("/update")
    public R update(@RequestBody Remark remark){
        log.info("--------- RemarkController | update | input : {}", JSON.toJSON(remark));
        if(null == remark.getId() || remark.getId() <= 0){
            return R.fail("参数错误:ID未传入");
        }
        int row = remarkService.update(remark);
        if(row <= 0){
            return  R.fail("修改失败");
        }
        return R.ok("修改成功");
    }
}
